package com.afd.ozblip.activity;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.afd.ozblip.animation.TabAnimationListener;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.update.UpdateService;
import com.afd.ozblip.update.Version;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.StringUtil;
import com.alibaba.fastjson.JSON;

public class IndexActivity extends FragmentActivity implements View.OnClickListener
{
	
	// XXX 常量
	/******************** 常量 ***************************/
	public static final String INTENT_TAB_CHANGE = "INTENT_TAB_CHANGE";
	
	/**
	 * Tab文字
	 */
	private TextView tabText[];
	
	/**
	 * Tab图片
	 */
	private ImageView tabImage[];
	
	public FragmentTabHost mTabHost = null;
	
	// tab索引
	public int oldIndex;
	
	public int nowIndex;
	
	private Activity mActivity;
	
	/****************** 数据变量 **************************/
	private Location location;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.maintabs);
		mActivity = this;
		oldIndex = -1;
		nowIndex = 0;
		// 获取参数
		getBundle();
		makeTab();
		// 获取版本更新
		requestUpdateData();
	}
	
	/**
	 * 获取传递的参数
	 */
	private void getBundle()
	{
		// Intent intent = getIntent();
	}
	
	private void makeTab()
	{
		// Intent search = new Intent(this, SearchFragment.class);
		// search.putExtra("location", location);
		// Intent top = new Intent(this, TopActivity.class);
		// Intent sign = new Intent(this, SignBusinessListActivity.class);
		// Intent user = new Intent(this, UserUnloginActivity.class);
		// Intent me = new Intent(this, MoreActivity.class);
		
		mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
		mTabHost.getTabWidget().setVisibility(View.GONE); // 隐藏系统的TabWidget
		mTabHost.addTab(addSpec("mhome_tab", R.string.index_bottom_home, R.drawable.nav_menu_search_style),
				SearchFragment.class, null);
		mTabHost.addTab(addSpec("mhot_tab", R.string.index_bottom_home, R.drawable.nav_menu_top_style), TopFragment.class,
				null);
		mTabHost.addTab(addSpec("msort_tab", R.string.index_bottom_home, R.drawable.nav_menu_sign_style),
				SignBusinessListFragment.class, null);
		mTabHost.addTab(addSpec("mlike_tab", R.string.index_bottom_home, R.drawable.nav_menu_user_style),
				UserCenterFragment.class, null);
		mTabHost.addTab(addSpec("mme_tab", R.string.index_bottom_home, R.drawable.nav_menu_more_style), MoreFragment.class,
				null);
		
		tabText = new TextView[5];
		tabText[0] = (TextView) findViewById(R.id.tv_main_menu_text_home);
		tabText[1] = (TextView) findViewById(R.id.tv_main_menu_text_hot);
		tabText[2] = (TextView) findViewById(R.id.tv_main_menu_text_category);
		tabText[3] = (TextView) findViewById(R.id.tv_main_menu_text_like);
		tabText[4] = (TextView) findViewById(R.id.tv_main_menu_text_me);
		
		tabImage = new ImageView[5];
		tabImage[0] = (ImageView) findViewById(R.id.img_main_menu_bg_home);
		tabImage[1] = (ImageView) findViewById(R.id.img_main_menu_bg_hot);
		tabImage[2] = (ImageView) findViewById(R.id.img_main_menu_bg_category);
		tabImage[3] = (ImageView) findViewById(R.id.img_main_menu_bg_like);
		tabImage[4] = (ImageView) findViewById(R.id.img_main_menu_bg_me);
		for (int i = 0; i < 5; i++)
		{
			tabText[i].setOnClickListener(this);
		}
		
	}
	
	public TextView[] getTabTextArr()
	{
		return this.tabText;
	}
	
	public ImageView[] getTabImageArr()
	{
		return this.tabImage;
	}
	
	private TabHost.TabSpec addSpec(String paramString, int paramInt1, int paramInt2)
	{
		return mTabHost.newTabSpec(paramString).setIndicator(getString(paramInt1), getResources().getDrawable(paramInt2));
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		// getTabHost().setCurrentTab(nowIndex);
	}
	
	// @Override
	// protected void onNewIntent(Intent intent) {
	// super.onNewIntent(intent);
	// int tabIndex = intent.getIntExtra(INTENT_TAB_CHANGE, -1);
	// if (tabIndex != -1) {
	// if (tabIndex == 3) {
	// BaseActivity.commonContent = intent
	// .getByteArrayExtra("content");
	// }
	// // getTabHost().setCurrentTab(tabIndex);
	// }
	// }
	
	@Override
	public void onClick(View v)
	{
		oldIndex = nowIndex;
		TranslateAnimation translateanimation = new TranslateAnimation(0.0F, v.getLeft() - tabText[oldIndex].getLeft(),
				0.0F, 0.0F);
		translateanimation.setDuration(200L);
		translateanimation.setFillAfter(false);
		translateanimation.setFillBefore(false);
		tabImage[oldIndex].startAnimation(translateanimation);
		translateanimation.setAnimationListener(new TabAnimationListener(this, v));
	}
	
	private long mExitTime = 0;
	
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			if ((System.currentTimeMillis() - mExitTime) > 2000)
			{
				Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				mExitTime = System.currentTimeMillis();
			}
			else
			{
				finish();
				System.exit(0);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode)
		{
			case 500:
				if (resultCode == Activity.RESULT_OK)
				{
					FragmentManager fm = getSupportFragmentManager();
					FragmentTransaction ft = fm.beginTransaction();
					UserCenterFragment ucf = (UserCenterFragment) fm.findFragmentByTag("mlike_tab");
					ft.attach(ucf);
					mTabHost.setCurrentTabByTag("mlike_tab");
					mTabHost.invalidate();
				}
				break;
		}
		
	}
	
	/********************** 版本更新 ************************/
	// 版本数据
	private Version version;
	
	/**
	 * 获取版本更新数据
	 */
	private void requestUpdateData()
	{
		AsyncLoadData ald = new AsyncLoadData(mActivity, "", new AsyncAction()
		{
			
			@Override
			public void doLoad() throws Exception
			{
				// 获取提交参数
				Map<String, Object> addDishParamMap = new HashMap<String, Object>();
				// 发送请求
				byte[] bRecommend = HttpUtil.requestByPost(mActivity, Constants.UPDATE_API, addDishParamMap);
				if (bRecommend != null)
				{
					String jsonStr = new String(bRecommend, "UTF-8");
					version = JSON.parseObject(jsonStr, Version.class);
				}
			}
			
			@Override
			public void loadEnd() throws Exception
			{
				if (version != null)
				{
					if (!StringUtil.isNullOrEmpty(version.getAppVersion()))
					{
						if (!getVersion().equals(version.getAppVersion()))
						{
							if (version.getMust() == 1)
							{
								tipDownloadLastAPK();
							}
						}
					}
				}
			}
			
		});
		ald.execute(0);
		
	}
	
	/**
	 * 获取版本号
	 * 
	 * @return 当前应用的版本号
	 */
	public String getVersion()
	{
		try
		{
			PackageManager manager = this.getPackageManager();
			PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
			String version = info.versionName;
			return version;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return "1.0";
		}
	}
	
	/**
	 * 提示下载最新版
	 */
	public void tipDownloadLastAPK()
	{
		
		// 发现新版本，提示用户更新
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(version.getName()).setMessage(version.getContent())
				.setPositiveButton("确定", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						// 开启更新服务UpdateService
						// 这里为了把update更好模块化，可以传一些updateService依赖的值
						// 如布局ID，资源ID，动态获取的标题
						Intent updateIntent = new Intent(mActivity, UpdateService.class);
						updateIntent.putExtra("title", "OzBlip");
						updateIntent.putExtra("downloadUrl", version.getAppUrl());
						startService(updateIntent);
					}
				}).setNegativeButton("取消", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.dismiss();
					}
				});
		alert.create().show();
	}
}
